package sys.transport;

import sys.message.*;

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
import java.util.concurrent.*;

public class MessageReceiverPOP3 implements MessageReceiver
{
    public String server, port, user, password;

    public MessageReceiverPOP3(String server, String port, String user, String password)
    {
        this.server = server;
        this.port = port;
        this.user = user;
        this.password = password;
    }
    
    public ConcurrentLinkedQueue<UniMessage> receive()
    {
        Store store     =   null;
        Folder folder   =   null;
        ConcurrentLinkedQueue<UniMessage>   messages   =   new ConcurrentLinkedQueue<UniMessage>();

        try
        {
            Properties props = System.getProperties();
            Session session = Session.getDefaultInstance(props, null);

            store = session.getStore("pop3");
            store.connect(server, Integer.parseInt(port), user, password);
            
            folder = store.getDefaultFolder();
            if (folder == null) throw new Exception("No default folder");

            folder = folder.getFolder("INBOX");
            if (folder == null) throw new Exception("No POP3 INBOX");

            folder.open(Folder.READ_WRITE);

            Message[] msgs = folder.getMessages();
            System.out.println("Got " + msgs.length + " messages"); 

            for (int i = 0; i < msgs.length; i++)
            {
                messages.add(new JSONMessage( msgs[i].getFrom()[0].toString(),
                                            msgs[i].getRecipients(Message.RecipientType.TO)[0].toString(),
                                            msgs[i].getSubject(),
                                            (String)msgs[i].getContent() ));
                msgs[i].setFlag(Flags.Flag.DELETED, true);
            }
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
        finally
        {
            try
            {
                if (folder!=null) folder.close(true);
                if (store!=null) store.close();
            }
            catch (Exception ex2) {ex2.printStackTrace();}
        }
        return messages;
    }
}

